package com.example.headlines.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.headlines.MainActivity;
import com.example.headlines.R;
import com.example.headlines.api.Api;
import com.example.headlines.api.ApiConfig;
import com.example.headlines.api.TtitCallback;
import com.example.headlines.databinding.ActivityLoginBinding;
import com.example.headlines.entity.LoginResponse;
import com.example.headlines.util.StringUtils;
import com.google.gson.Gson;

import java.util.HashMap;

import okhttp3.OkHttpClient;

public class LoginActivity extends BaseActivity {
    private ActivityLoginBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = binding.etAccount.getText().toString().trim();
                String pwd = binding.etPwd.getText().toString().trim();
                login(account, pwd);
            }
        });
    }

    @Override
    protected void initData() {

    }

    private void login(String account, String pwd) {
        if (StringUtils.isEmpty(account)) {
            showToast("请输入账号");
            return;
        }
        if (StringUtils.isEmpty(pwd)) {
            showToast("请输入密码");
            return;
        }

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("mobile", account);
        params.put("password", pwd);

        Api.config(ApiConfig.LOGIN, params).postRequest(this,new TtitCallback() {
            @Override
            public void onSuccess(final String res) {
                Log.e("onSuccess", res);
                Gson gson = new Gson();
                LoginResponse loginResponse = gson.fromJson(res, LoginResponse.class);
                if (loginResponse.getCode() == 0) {
                    String token=loginResponse.getToken();
                    saveStringToSp("token",token);
                    saveStringToSp("mname", (String) params.get("mobile"));
//                    navigateTo(HomeActivity.class);
                    navigateToWithFlag(HomeActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

                    showToastSync("登录成功");

                } else {
                    showToastSync("用户名或密码错误");
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}
